/*
* check user current login status
* res.isLogin: default value is false
* */

const { $request } = require('../plugin/request'),
      { baseUrl } = require('../config/api.conf');

const checkLogin = (req, res, next) => {

    res.isLogin = false; // 默认未登录

    var token = req.cookies['USER_TOKEN'] || '';
    $request({
        method: 'get',
        baseUrl: baseUrl,
        url: '/auth/judgeUserLoginBytoken',
        data: {
            token: token
        }
    }).finally(result => {
        res.isLogin = JSON.parse(result);
        // 已登录用户，返回用户的基本信息cookie
        if(res.isLogin === true && req.cookies['USER_BASE']){
            const USER_BASE = req.cookies['USER_BASE'].split(',');
            res.USER_CODE = USER_BASE[0];
            res.USER_NAME = USER_BASE[1];
            res.USER_HEAD = USER_BASE[2];
        }

        next()
    })
};

module.exports = checkLogin;